package com.blb.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Aspect
@EnableAspectJAutoProxy
@Configuration
public class TransactionAspect {

    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Around("execution(* com.blb.service.impl.*ServiceImpl.*(..)) && @annotation(com.blb.config.MyTransactional)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //启动事务
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        System.out.println("执行了AOP");
        //执行原方法
        Object obj = joinPoint.proceed();
        //提交事务
        transactionManager.commit(status);
        return obj;
    }
}
